package com.eliteams.quick4j.core.entity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.eliteams.quick4j.app.model.LogUUid;

public class SiteMapUtils {
	private static Log logger1 = LogFactory.getLog("mylogger1");
	
    private long pointer; //上次文件大小  
    private static final Logger logger = LoggerFactory.getLogger(SiteMapUtils.class);  
    private static SimpleDateFormat  dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");  
    static ScheduledExecutorService  exec = Executors.newScheduledThreadPool(1); 
    static List<Object> list = new ArrayList<Object>();
    
    /**
     * 获取UUID
     */
    public static String getUUid(){
    	UUID uuid = UUID.randomUUID();
    	return uuid.toString();
    }
    
    public List<Object> realtimeShowLog(final File logFile,List<LogUUid> listuuid) throws Exception{  
    	pointer=0;
        if(logFile == null) {  
            throw new IllegalStateException("logFile can not be null");  
        }  
        //获得变化部分  
        try {  
        	long len = logFile.length();  
        	if(len < pointer){  
        		logger.info("Log file was reset. Restarting logging from start of file.");  
        		pointer = 0;  
        	}else{  
        		//指定文件可读可写  
        		RandomAccessFile  randomFile= new RandomAccessFile(logFile,"rw");  
        		  
//        		System.out.println("RandomAccessFile文件指针的初始位置:"+pointer);   
        		randomFile.seek(pointer);//移动文件指针位置   
        		String tmp = "";  
        		while((tmp = randomFile.readLine()) != null) {  
//        			System.out.println("info : " +new String(tmp.getBytes("ISO-8859-1"))); 
        			String obj = new String(tmp.getBytes("ISO-8859-1"));
        			for(LogUUid logUUid:listuuid){
        				String uuid_ = logUUid.getUuid();
        				if(obj.indexOf(uuid_) != -1 && obj.indexOf("http://") != -1){
        	        		String[] split = obj.split(" ");
        	        		
        	        		System.out.println("0:"+split[3]+" "+split[4]);
        	        		System.out.println("1:"+split[6]);
        	        		System.out.println("2:"+split[7]);
        	        		System.out.println("3:"+split[8]);
        	        	}else if(obj.indexOf(uuid_) != -1){
        	        		String[] split = obj.split(" ");
        	        		
        	        		System.out.println("0:"+split[3]+" "+split[4]);
        	        		System.out.println("1:"+split[6]);
        	        		System.out.println("2:"+split[7]);
        	        	}
        			}
        			list.add(new String(tmp.getBytes("utf-8")));
        			pointer = randomFile.getFilePointer();  
        		}
        		randomFile.close();  
        	}  
        } catch (Exception e) {  
        	//实时读取日志异常，需要记录时间和lastTimeFileSize 以便后期手动补充  
        	logger.error(dateFormat.format(new Date())  + " File read error, pointer: "+pointer);  
        } 
         
        return list; 
    }
	
	public static void getXMLs(String url_,String uuId){
		URL url;  
        int responsecode;  
        HttpURLConnection urlConnection=null;  
        BufferedReader reader=null;  
        String line; 
        String xml = "";
        try {
			url=new URL(url_);
			urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); //防止报403错误。  
			//获取服务器响应代码  
			responsecode=urlConnection.getResponseCode();  
			if(responsecode==200){  
				//得到输入流，即获得了网页的内容   
				reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));  
				while((line=reader.readLine())!=null){  
					xml += line;
				}  
				SiteMapUtils.getXMLsToHTML(xml,uuId);
			}  
		} catch (MalformedURLException e) {
			logger1.info(" "+uuId+" "+e);
		} catch (IOException e) {
			logger1.info(" "+uuId+" "+e);
		}  
	}
	
	public static void getXMLsToHTML(String xml,String uuId){
		Document document;
		Element rootElement;
		Element fooElement;
		int a = 0;
		try {
			Calendar cal=Calendar.getInstance();
	        cal.add(Calendar.DATE,-1);
	        Date time=cal.getTime();
	        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(time);
	        String[] split = yesterday.split("-");
	        String str="";
	        for (String string : split) {
	        	str+=string;
			}
			
			document = DocumentHelper.parseText(xml);
			rootElement=document.getRootElement();
			for(Iterator i=rootElement.elementIterator("sitemap");i.hasNext();){
				fooElement=(Element)i.next();
				String urls=fooElement.elementText("loc");//url  对它进行截取
				a++;
				
				String string = urls.substring(44,52);
				if(string.equals(str)){//拿昨天的日期作比较，例如20171206
					SiteMapUtils.getHTMLs(urls, a,uuId);
				}
			}
		} catch (DocumentException e) {
			logger1.info(" "+uuId+" "+e);
		}
	}
	
	public static void getHTMLs(String urls,int a,String uuId){
		URL url;  
		int responsecode;  
		HttpURLConnection urlConnection=null;  
		BufferedReader reader=null;  
		String line;
		//获取年月日信息
		Calendar now = Calendar.getInstance();
		String date = now.get(Calendar.YEAR)+String.valueOf((now.get(Calendar.MONTH)+1))+now.get(Calendar.DAY_OF_MONTH);
		if(urls != null){
			try {
				url=new URL(urls);
				urlConnection = (HttpURLConnection)url.openConnection();
				urlConnection.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); //防止报403错误。  
				//获取服务器响应代码  
				responsecode=urlConnection.getResponseCode();  
				if(responsecode==200){ 
					//得到输入流，即获得了网页的内容   
					reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); 
					BufferedWriter writer = new BufferedWriter(new FileWriter("E:/testsitemap/"+date+a+".xml"));
					while((line=reader.readLine())!=null){  
						writer.write(line); 
						writer.newLine();
					}  
					writer.flush();
					writer.close();
					reader.close();
				}else{  
					logger1.info(" "+uuId+" "+responsecode);  
				}  
			} catch (MalformedURLException e) {
				logger1.info(" "+uuId+" "+e);
			}catch (IOException e) {
				logger1.info(" "+uuId+" "+e);
			}  
		}
	}
	
	/**
	 * mybatis进行模糊查询进行字符替换
	 * mybatis模糊查询防止SQL注入(字符替换)
	 * @param keyword
	 * @return
	 */
	public static String transfer(String keyword){
		if(keyword.contains("%") || keyword.contains("_")){
			keyword = keyword.replaceAll("\\\\", "\\\\\\\\")
					.replaceAll("\\%", "\\\\%")
					.replaceAll("\\_", "\\\\_");
		}
		return keyword;
	}
}
